package com.by.interceptor;

import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ServivE
 * @version 0.1
 * @className AuthInterceptor
 * @description
 * @date 2024/10/30 14:30
 * @since jdk17
 */
public class AuthInterceptor implements HandlerInterceptor {
    /**
     * 方法执行前调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //获取请求头 auth
        String auth = request.getHeader("Authorization");
        //乱码处理
        response.setContentType("text/plain;charset=utf-8");


        if (null == auth) {
            //提示
            response.getWriter().write("无权访问");
            return false;
        }
        //得到的值 basic ............
        String[] tmp = auth.split("\\s+");//  \\s+ 代表空格
        String enstr = tmp[1];//这是加密后的字符串
        //解密
        String userpwd = new String(Base64Utils.decode(enstr.getBytes()));
        tmp = userpwd.split(":");
        String username = tmp[0];
        String password = tmp[1];

        if ("admin".equals(username) && "123456".equals(password)) {
            return true;//放行
        }else {
            //授权信息错误
            response.getWriter().write("账户信息错误");
            return false;
        }

    }
}
